/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.servinf.ani.sincronizador;

import com.servinf.ani.sincronizador.utils.LogHelper;
import com.servinf.ani.sincronizador.utils.PropertiesHelper;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author mortiz
 */
public class BackUp_RestoreDB {
    
      /*
       * COMANDO PARA BACK UP DE LA BASE DE DATOS
       * 
        C:\Program Files\PostgreSQL\9.1\bin>pg_dump -i -h localhost -p 5432 -U postgres
        -F c -b -v -f C:\prueba.backup ani_admin

        pg_dump -i -h localhost -p 5432 -U postgres -F c -b -v -f 
        "/usr/local/backup/10.70.0.61.backup" old_db

        -p, –port=PORT database server port number
        -i, –ignore-version proceed even when server version mismatches
        -h, –host=HOSTNAME database server host or socket directory
        -U, –username=NAME connect as specified database user
        -W, –password force password prompt (should happen automatically)
        -d, –dbname=NAME connect to database name
        -v, –verbose verbose mode
        -F, –format=c|t|p output file format (custom, tar, plain text)
        -c, –clean clean (drop) schema prior to create
        -b, –blobs include large objects in dump
        -v, –verbose verbose mode
        -f, –file=FILENAME output file name
    */
    
     public static void backUp() {
        try {
            //Del archivo properties se obtienen los parámentros de la base de datos.
            String pg_dump = PropertiesHelper.getInstance().getProperties().getProperty("postgreSQL.path");
            String backUpFolderString = PropertiesHelper.getInstance().getProperties().getProperty("postgreSQL.back_up.output");
            File backUpFolder = new File(backUpFolderString);
            if(!backUpFolder.exists()) {
                backUpFolder.mkdirs();
            }
            String jdbcUrl = PropertiesHelper.getInstance().getProperties().getProperty("jdbc.url");
            //Leer el host de la url
            int i = jdbcUrl.indexOf('/') + 2;
            int j = jdbcUrl.indexOf(':',i);
            String host = jdbcUrl.substring(i, j);
            int k = jdbcUrl.indexOf('/',j);
            String port = jdbcUrl.substring(j + 1, k);
            String backUpFileName = backUpFolderString + "BackUp_ANI_" + now() + ".backup";
            String username = PropertiesHelper.getInstance().getProperties().getProperty("jdbc.username");
            String database = jdbcUrl.substring(jdbcUrl.lastIndexOf('/') + 1);
            Runtime r = Runtime.getRuntime();
            Process p;
            ProcessBuilder pb;
            r = Runtime.getRuntime();
            pb = new ProcessBuilder( 
                pg_dump,
                "-i",
                "-h", host,
                "-p", port,
                "-U", username,
                "-F", "c",
                "-b", 
                "-v",
                "-f", backUpFileName,
                database);
            pb.redirectErrorStream(true);
            p = pb.start();
            InputStream is = p.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String ll;
            while ((ll = br.readLine()) != null) {
             LogHelper.Log(LogHelper.INFO, ll, null);
            }                    
        } catch (IOException ex) {
            ex.printStackTrace();
            try {
                LogHelper.Log(LogHelper.ERROR, ex.getMessage(), ex);
            } catch (IOException ex1) {
                Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex1);
            }
        }
        
    }
   
    private static String now() {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("HH-mm-yyyy-MM-dd");
        return sdf.format(cal.getTime());
    }
   
    //RESTORE COMMAND 
    //C:/Program Files/PostgreSQL/9.1/bin\pg_restore.exe --host localhost --port 5432 --username "postgres" --dbname "ani_admin" --no-password  --verbose "C:\back_ups_ANI\BackUp_ANI_15-42-2015-02-10.backup"
    
}
